<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\DepartmentService;
use app\service\ProjectService;
use app\service\UserService;
use think\facade\Validate;
use think\Request;

class ProjectController extends BaseController
{
    /**
     * 项目列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $userId = $request->param('userId', '');
      $departmentId = $request->param('departmentId', []);
      $conditions = [
        ['status', 0, '<>']
      ];
      if ($departmentId) {
        $conditions[] = ['department_id', $departmentId, 'IN'];
      }
      $list = [];
      $res = ProjectService::getInstance()->getProjectByCondition($conditions);
      // 获取用户
      $userList = UserService::getInstance()->getUserByCondition();
      $userList = array_column($userList, null, 'id');
      // 获取部门
      $departmentList = DepartmentService::getInstance()->getDepartmentByCondition();
      $departmentList = array_column($departmentList, null, 'id');
      foreach ($res as $value) {
        $assignUser = explode(',', $value['project_user_ids']);
        $arrName = [];
        $arr = [];
        foreach ($assignUser as $u) {
          $user = isset($userList[$u]) ? $userList[$u] : '';
          if ($user) {
            $arrName[] = $user['truename'];
            $arr[] = $user['id'];
          }
        }
        $value['project_user'] = implode(',', $arrName);
        $value['department_name'] = isset($departmentList[$value['department_id']]) ? $departmentList[$value['department_id']]['department_name'] : '';
        if ($userId && !in_array($userId, $arr) && $userList[$userId]['role_id'] !== 1) {
          continue;
        }
        $list[] = $value;
      }
      // 分页
      $count = count($list); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];
      $data = array_slice($list, $start, intval($pageSize));
      return $this->send200ResponseWithPager($data,$pager);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $data['project_name'] = $request->param('project_name', '');
      $data['project_user_ids'] = $request->param('project_user_ids', '');
      $data['department_id'] = $request->param('department_id', '');
      $data['desc'] = $request->param('desc', '');
      $validate = Validate::rule([
        'project_name' => 'require',
        'department_id' => 'require',
        'project_user_ids' => 'require'
      ])->message([
        'project_name.require' => '项目名不能为空',
        'department_id.require' => '部门不能为空',
        'project_user_ids.require' => '项目相关人员不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $result = ProjectService::getInstance()->createProject($data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      $conditions = [
        ['status', 0, '<>'],
        ['id', $id, '=']
      ];
      $list = ProjectService::getInstance()->getProjectByCondition($conditions);
      $data = [];
      if ($list) {
        $data = $list[0];
        $data['project_user_ids'] = explode(',', $data['project_user_ids']);
      }
      return $this->send200Response($data);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $data['project_name'] = $request->param('project_name', '');
      $data['project_user_ids'] = $request->param('project_user_ids', '');
      $data['department_id'] = $request->param('department_id', '');
      $data['desc'] = $request->param('desc', '');
      $validate = Validate::rule([
        'project_name' => 'require',
        'department_id' => 'require',
        'project_user_ids' => 'require'
      ])->message([
        'project_name.require' => '项目名不能为空',
        'department_id.require' => '部门不能为空',
        'project_user_ids.require' => '项目相关人员不能为空'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $result = ProjectService::getInstance()->updateProject($id, $data);
      if ($result['status']) {
        return $this->send200Response('ok');
      } else {
        return $this->send400Response($result['msg']);
      }

    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
      $result = ProjectService::getInstance()->deleteProject($id);
      if ($result['status']) {
        return $this->send200Response('ok');
      }
      return $this->send400Response($result['msg']);
    }
}
